package com.selfdiscipline.ui.screens.task

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.selfdiscipline.R
import com.selfdiscipline.ui.components.common.PriorityButton
import com.selfdiscipline.ui.components.common.TopAppBarCommon
import java.time.LocalDateTime

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TaskAddEditScreen(
    taskId: Long? = null,
    navigateBack: () -> Unit,
    viewModel: TaskAddEditViewModel = hiltViewModel()
) {
    // 如果有taskId表示编辑，否则是添加
    val isEditMode = taskId != null
    
    // 如果是编辑模式，加载任务数据
    LaunchedEffect(taskId) {
        if (isEditMode && taskId != null) {
            viewModel.loadTask(taskId)
        }
    }
    
    val uiState by viewModel.uiState.collectAsState()
    
    Scaffold(
        topBar = {
            TopAppBarCommon(
                title = stringResource(id = if (isEditMode) R.string.edit_task else R.string.add_task),
                onNavigationClick = navigateBack
            )
        },
        floatingActionButton = {
            Button(
                onClick = {
                    viewModel.saveTask()
                    navigateBack()
                },
                enabled = uiState.title.isNotBlank()
            ) {
                Icon(
                    imageVector = Icons.Filled.Save,
                    contentDescription = null
                )
                Spacer(modifier = Modifier.width(8.dp))
                Text(text = stringResource(id = R.string.save))
            }
        }
    ) { paddingValues ->
        if (uiState.isLoading) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues),
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator()
            }
        } else {
            TaskAddEditContent(
                uiState = uiState,
                onTitleChange = viewModel::updateTitle,
                onDescriptionChange = viewModel::updateDescription,
                onPriorityChange = viewModel::updatePriority,
                onDueDateChange = viewModel::updateDueDate,
                onEstimatedTimeChange = viewModel::updateEstimatedTime,
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues)
                    .verticalScroll(rememberScrollState())
                    .padding(16.dp)
            )
        }
    }
}

@Composable
fun TaskAddEditContent(
    uiState: TaskAddEditUiState,
    onTitleChange: (String) -> Unit,
    onDescriptionChange: (String) -> Unit,
    onPriorityChange: (Int) -> Unit,
    onDueDateChange: (LocalDateTime?) -> Unit,
    onEstimatedTimeChange: (Int) -> Unit,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier,
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        // 标题输入
        OutlinedTextField(
            value = uiState.title,
            onValueChange = onTitleChange,
            label = { Text(stringResource(id = R.string.task_title)) },
            modifier = Modifier.fillMaxWidth(),
            singleLine = true
        )
        
        // 描述输入
        OutlinedTextField(
            value = uiState.description ?: "",
            onValueChange = onDescriptionChange,
            label = { Text(stringResource(id = R.string.task_description)) },
            modifier = Modifier.fillMaxWidth(),
            minLines = 3,
            maxLines = 5
        )
        
        // 优先级选择
        Text(
            text = stringResource(id = R.string.task_priority),
            style = MaterialTheme.typography.bodyLarge
        )
        
        // 使用三等分的优先级按钮
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            val buttonModifier = Modifier.width(100.dp) // 固定宽度
            
            // 高优先级按钮
            PriorityButton(
                text = "高",
                selected = uiState.priority == 2,
                onClick = { onPriorityChange(2) },
                color = MaterialTheme.colorScheme.error,
                modifier = buttonModifier
            )
            
            // 中优先级按钮
            PriorityButton(
                text = "中",
                selected = uiState.priority == 1,
                onClick = { onPriorityChange(1) },
                color = MaterialTheme.colorScheme.tertiary,
                modifier = buttonModifier
            )
            
            // 低优先级按钮
            PriorityButton(
                text = "低",
                selected = uiState.priority == 0,
                onClick = { onPriorityChange(0) },
                color = MaterialTheme.colorScheme.primary,
                modifier = buttonModifier
            )
        }
        
        // 预计时间
        OutlinedTextField(
            value = uiState.estimatedMinutes.toString(),
            onValueChange = { 
                val minutes = it.toIntOrNull() ?: 0
                onEstimatedTimeChange(minutes)
            },
            label = { Text(stringResource(id = R.string.task_estimated_time)) },
            modifier = Modifier.fillMaxWidth(),
            singleLine = true,
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
        )
        
        // TODO: 添加日期选择器，可选择截止日期
        // 这里需要添加日期选择的功能，但需要DatePicker等组件支持
    }
} 